<template>
  <div class="page sortData">
    <div class="sortData-header flex-r">
      <span>筛选：</span>
      <a-select :default-value="province" v-model='province' style="width: 112px;marginRight:0.1rem;color: #BFBFBF;"
        @change="handleProvinceChange">
        <a-select-option v-for='(provinceName,index) in provinceData' :key='index'>
          {{provinceName}}
        </a-select-option>
      </a-select>
      <a-select :default-value="city" v-model='city' style="width: 112px;marginRight:0.1rem;color: #BFBFBF;"
        @change="handleCityChange">
        <a-select-option v-for='(cityName,index) in cityData' :key='index'>
          {{cityName}}
        </a-select-option>
      </a-select>
      <a-select :default-value="town" v-model='town' style="width: 112px;marginRight:0.1rem;color: #BFBFBF;"
        @change="handleTownChange">
        <a-select-option v-for='(townName,index) in townData' :key='index'>
          {{townName}}
        </a-select-option>
      </a-select>
      <a-month-picker placeholder="请输入月份" :disabledDate="disabledMonth" @change="onChange"
        style="marginRight:0.1rem;" />
      <a-select default-value="请输入查询参数" style="width: 150px;marginRight:0.1rem;color: #BFBFBF;">
        <a-select-option v-for='(parameters,index) in params' :key="index" @click="searchData(parameters.name)">
          {{parameters.name}}
        </a-select-option>
      </a-select>
      <a-Button type="primary" @click='updataChart'>查询</a-Button>
    </div>
    <div class="sortData-content">
      <div class="chartH">
        <p>
          <span @click="changeChart(1)" :style="[{color:changeStyle == 2 ?'#A0A0A0':'#1F1F1F'},{
            borderBottom:changeStyle == 2 ?'':'2px solid #3A33D1'
          }]">时均时序图</span>
          <span @click="changeChart(2)" :style="[{color:changeStyle == 2 ?'#1F1F1F':'#A0A0A0'},{
            borderBottom:changeStyle == 2?'2px solid #3A33D1':''
          }]">月计均值图</span>
        </p>
        <div class="example">
          <a-spin size='large' :spinning="spinnings" />
        </div>
        <div class="chartL" id="chartL" v-show="changeStyle == 1">
        </div>
        <div id="chartH" v-show="changeStyle == 2">
        </div>
      </div>
      <div class="chartM">
        <p>污染统计日历 <span style="transform:scale(0.8) translateX(-10%);display:inline-block;width:60%;">
            *CO浓度单位为mg/m³ 其他颗粒物浓度单位为μg/m³ ，温度单位为°C，湿度单位为%。
          </span></p>
        <div class="example">
          <a-spin size='large' :spinning="spinnings" />
        </div>
        <div class="chartMtb">
          <div style="width: 4%;">
            <div v-for="(codeItem,index) in tableData" :key='index'
              style="height:20px;text-align: left;line-height: 20px;font-size: 12px;margin-bottom: 1px;font-family: PingFangSC, PingFangSC-Regular;font-weight: 400;margin-left: 15px;">
              <span>站点{{codeItem.code}}</span>
            </div>
          </div>
          <div style='width: 90%;font-size: 12px;'>
            <table border="1" style="width: 100%;margin-left: 10px;">
              <tr v-for="(tableItem,index) in tableData" :key='index'
                style="width:30px;height: 20px;line-height: 20px;text-align: center;">
                <td v-for="(item,index) in tableItem.value" :key='index'
                  :style="{background:areaConfig('AQI',item['AQI']).color}" style="width:30px;">
                  {{item[selectIte]}}
                </td>
              </tr>
            </table>
            <div style="width: 100%;margin-left: 10px;display: flex;justify-content: space-around;">
              <span v-for="(itemDate,index) in dateData" :key='index'>{{itemDate.time}}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import areaConfig from '../../../common/js/range.js'
import moment from 'moment'
import { Column, Line } from '@antv/g2plot'
import { stringTime } from '../../../common/js/commont.js'
import mixinSYZ from '../../../store/syz/mixinSYZ.js'
import getPCT from '../../../common/js/area.js'
export default {
  mixins: [mixinSYZ],
  data () {
    return {
      params: {},
      chartData: [],
      minTime: '',
      maxTime: '',
      historyData: {},
      selectItem: '',
      changeStyle: 1,
      provinceData: [],
      province: '请输入省',
      cityData: [],
      city: '请输入市',
      townData: [],
      town: '请输入区',
      spinning: true,
      chartHdata: [],
      histogramData: [],
      monthFirst: '',
      monthLast: '',
      dateData: [],
      tableData: [],
      selectIte: '',
      spinnings: false
    }
  },
  methods: {
    areaConfig (type, number) {
      return areaConfig(type, number)
    },
    moment,
    disabledMonth (current) {
      return current && current > moment().startOf('month')
    },
    onChange  (date, dateString) {
      this.monthFirst = moment(dateString).startOf('month').format('YYYY-MM-DD')
      this.monthLast = moment(dateString).endOf('month').format('YYYY-MM-DD')
      this.minTime = stringTime(new Date(this.monthFirst))
      this.maxTime = stringTime(new Date(this.monthLast))
    },
    //  获取用户设备接收参数
    changeSortData  () {
      const ts = stringTime(new Date())
      const data = {
        account: window.localStorage.getItem('account'),
        token: window.localStorage.getItem('token'),
        ts
      }
      this.getPointSortData(data).then(res => {
        this.params = res.data.data.slice(0, 5)
      })
    },
    //  获取历史数据（折线图）
    getPointHistory () {
      const ts = stringTime(new Date())
      const data = {
        account: window.localStorage.getItem('account'),
        city: this.city,
        datetype: 'H',
        max_time: this.maxTime,
        min_time: this.minTime,
        params: this.selectItem,
        province: this.province,
        token: window.localStorage.getItem('token'),
        town: this.town,
        ts
      }
      this.getHistoryData(data).then(res => {
        this.historyData = res.data.data
        const chartMap = Object.keys(res.data.data)
        chartMap.forEach(items => {
          this.historyData[items].forEach(item => {
            this.chartData.push({
              code: item.code,
              time: item.time,
              [this.selectItem]: +item[this.selectItem]
            })
          })
        })
        if (this.chartData.length > 0) {
          this.spinnings = false
        }
        this.initChartL()
      })
    },

    //  获取历史数据（污染统计图）
    getPointHistoryM  () {
      const ts = stringTime(new Date())
      const data = {
        account: window.localStorage.getItem('account'),
        city: this.city,
        datetype: 'D',
        max_time: this.maxTime,
        min_time: this.minTime,
        params: 'PM2.5,AQI,PM1,PM10,TSP',
        // params: this.selectItem ,
        province: this.province,
        token: window.localStorage.getItem('token'),
        town: this.town,
        ts
      }
      this.getHistoryData(data).then(res => {
        this.historyData = res.data.data
        this.codeData = Object.keys(res.data.data)
        if (this.codeData.length > 0) {
          const index = this.codeData[1]
          this.historyData[index].forEach(item => {
            const datetime = item.time.substring(5, 10)
            this.dateData.push({
              time: datetime
            })
          })
          this.codeData.forEach(item => {
            this.tableData.push({
              value: this.historyData[item],
              code: item
            })
          })
          if (this.tableData.length > 0) {
            this.spinnings = false
          }
        }
      })
    },
    //  获取历史数据（柱状图）
    getPointHistoryH  () {
      const ts = stringTime(new Date())
      const data = {
        account: window.localStorage.getItem('account'),
        city: this.city,
        datetype: 'M',
        max_time: this.monthLast,
        min_time: this.monthFirst,
        params: this.selectItem,
        province: this.province,
        token: window.localStorage.getItem('token'),
        town: this.town,
        ts
      }
      this.getHistoryData(data).then(res => {
        const chartHap = Object.keys(res.data.data)
        chartHap.forEach(item => {
          if (res.data.data[item].length > 0) {
            this.histogramData.push({
              code: res.data.data[item][0].code,
              [this.selectItem]: +res.data.data[item][0][this.selectItem]
            })
          }
        })
        this.initChartH()
      })
    },

    // 渲染柱状图
    initChartH  () {
      if (this.chartH) {
        this.chartH.update()
      } else {
        this.createChartH()
        this.chartH.render()
      }
    },

    // 创建柱状图
    createChartH  () {
      var self = this
      this.chartH = new Column('chartH', {
        data: self.histogramData,
        xField: 'code',
        yField: self.selectItem,
        xAxis: {
          label: {
            autoHide: true,
            autoRotate: false
          }
        },
        meta: {
          type: {
            alias: '类别'
          },
          sales: {
            alias: '污染指数'
          }
        }
      })
    },
    //  渲染折线图
    initChartL  () {
      if (this.line) {
        this.line.update()
      } else {
        this.creatChartL()
        this.line.render()
      }
    },
    //  创建折线图
    creatChartL () {
      var self = this
      this.line = new Line('chartL', {
        data: self.chartData,
        padding: 'auto',
        xField: 'time',
        yField: self.selectItem,
        seriesField: 'code',
        xAxis: {
          tickCount: 5
        },
        slider: {
          start: 0.1,
          end: 0.5
        },
        yAxis: {
          label: {
            // 数值格式化为千分位
            formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`)
          }
        }
      })
    },
    //  获取下拉选项与查询数据建立联系
    searchData  (name) {
      document.getElementsByClassName('ant-select-selection-selected-value')[3].style.color = '#595959'
      this.selectItem = name
    },
    //  查询更新图表数据
    updataChart () {
      this.spinning = true
      this.getPointHistory()
      this.chartData = []
      if (this.line) {
        this.line.options.yField = this.selectItem
        this.line.options.data = []
        this.line.options.data = this.chartData
      }

      this.getPointHistoryM()
      this.selectIte = this.selectItem
      this.tableData = []
      this.dateData = []
      this.getPointHistoryH()
      this.histogramData = []
      if (this.chartH) {
        this.chartH.options.yField = this.selectItem
        this.chartH.options.data = []
        this.chartH.options.data = this.histogramData
      }
    },
    //  切换改变图表类型
    changeChart (id) {
      if (id === 1) {
        this.changeStyle = id
        // this.initChartL()
      }
      if (id === 2) {
        this.changeStyle = id
      }
    },

    //  获取省，市，区相关数据
    getArea () {
      this.provinceData = getPCT.getProvince()
    },
    handleProvinceChange  (value1) {
      document.getElementsByClassName('ant-select-selection-selected-value')[0].style.color = '#595959'
      this.province = this.provinceData[value1]
      this.cityData = getPCT.getCity(this.provinceData[value1])
      this.handleCityChange(0)
    },
    handleCityChange  (value2) {
      document.getElementsByClassName('ant-select-selection-selected-value')[1].style.color = '#595959'
      this.city = this.cityData[value2]
      this.townData = getPCT.getArea(this.province, this.city)
      this.handleTownChange(0)
    },
    handleTownChange  (value3) {
      document.getElementsByClassName('ant-select-selection-selected-value')[2].style.color = '#595959'
      this.town = this.townData[value3]
    }
  },
  mounted () {
    this.changeSortData()
    this.getArea()
  }
}
</script>

<style lang='less' scoped>
  .sortData {
    color: #000000;
    font-size: 0.16rem;
  }
  .sortData-header {
    padding: 0rem 0.32rem;
    min-height: 38px;
    width: 100%;
    background: white;
    height: 0.64rem;
  }
  .sortData-content {
    width: 100%;
    height: calc(100% - 0.64rem);
    overflow: auto;
    @media (max-width: 1024px) {
      height: calc(100% - 38px);
    }
    padding: 0.1rem;
    .chartH {
      widh: 100%;
      min-height: calc(50% - 0.05rem);
      background: white;
      border-radius: 0.12rem;
      margin-bottom: 0.12rem;
      padding: 0.1rem;
      position: relative;
      p {
        font-weight: 600;
        height: 0.36rem;
        min-height: 12px;
        margin: 0;
        padding: 0.03rem 0.16rem;
        span {
          height: 20px;
          margin-right: 32px;
          display: inline-block;
          cursor: pointer;
          padding-bottom: 25px;
        }
      }
      #chartH {
        width: 100%;
        min-height: calc(100% - 0.4rem);
      }
      .chartL {
        width: 100%;
        min-height: calc(100% - 0.4rem);
      }
      .example {
        position: absolute;
        left: 45%;
        top: 45%;
      }
    }
    .chartM {
      widh: 100%;
      min-height: calc(50% - 0.05rem);
      padding: 0.1rem;
      background: white;
      border-radius: 0.12rem;
      position: relative;
      p {
        font-weight: 600;
        margin: 0;
        height: 0.36rem;
        min-height: 12px;
        padding: 0.03rem 0.16rem;
        span {
          font-size: 0.12rem;
          color: #8f8f8f;
          font-weight: 200;
        }
      }
      .example {
        position: absolute;
        left: 45%;
        top: 45%;
      }
      .chartMtb {
        display: flex;
      }
    }
  }
</style>
